package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.计算dataList
        List<LocalDate> localDatesList=new ArrayList<>();
        localDatesList.add(begin);
        while  (!begin.equals(end)){
            //计算日期后一天对应日期
            begin=begin.plusDays(1);
            localDatesList.add(begin);
        }
        String dateList="";
        for (LocalDate localDate : localDatesList) {
            dateList+=localDate.toString();
            dateList+=",";
        }
        dateList=dateList.substring(0,dateList.length()-1);

        //2.查询营业额
        List<Double> localAmountList=new ArrayList<>();
        for (LocalDate localDate : localDatesList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime =LocalDateTime.of(localDate,LocalTime.MAX);
            Double amountByDay = orderMapper.getAmountByDay(beginTime, endTime);
            localAmountList.add(amountByDay==null?0.0:amountByDay);
        }
        String turnoverList="";
        for (Double localAmount : localAmountList) {
            turnoverList+=localAmount.toString();
            turnoverList+=",";
        }
        turnoverList=turnoverList.substring(0,turnoverList.length()-1);
        return new  TurnoverReportVO(dateList,turnoverList);
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.计算dataList
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while  (!begin.equals(end)){
            //计算日期后一天对应日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //2.计算totalUserList
        List<Integer> totalUserList=new ArrayList<>();
        List<Integer> newUserList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            LocalDateTime endTime =LocalDateTime.of(localDate,LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endTime);
            totalUserList.add(userMapper.countByMap(map));
            map.put("begin",beginTime);
            newUserList.add(userMapper.countByMap(map));


        }
        return UserReportVO.builder().dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,",")).newUserList(StringUtils.join(newUserList,",")).build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //1.计算dataList
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while  (!begin.equals(end)){
            //计算日期后一天对应日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //2.计算orderCountList和validOrderCountList
        List<Integer>orderCountList=new ArrayList<>();
        List<Integer>validOrderCountList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            Map map=new HashMap();
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime =LocalDateTime.of(localDate,LocalTime.MAX);
            map.put("begin",beginTime);
            map.put("end",endTime);
            orderCountList.add(orderMapper.countByMap(map));
            map.put("status", Orders.COMPLETED);
            validOrderCountList.add(orderMapper.countByMap(map));
        }
        //3.获取订单总数，有效订单总数，订单完成率
        //订单总数
        Integer totalOrderCount=0;
        //有效订单数
        Integer validOrderCount=0;
        //订单完成率
        Double orderCompletionRate=0.0;
        for (Integer i : orderCountList) {
            totalOrderCount+=i;
        }
        for (Integer i : validOrderCountList) {
            validOrderCount+=i;
        }
        if(totalOrderCount!=0){
            orderCompletionRate= (double) (validOrderCount/totalOrderCount);
        }
        return OrderReportVO.builder().dateList(StringUtils.join(dateList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCompletionRate(orderCompletionRate)
                .build() ;
    }

    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> goodsSalesDTOList=new ArrayList<>();
        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);
        goodsSalesDTOList=orderMapper.getSalesTop10(beginTime,endTime);
        List<String> nameList = goodsSalesDTOList.stream().map(o -> o.getName()).collect(Collectors.toList());
        List<Integer> numberList=goodsSalesDTOList.stream().map(o->o.getNumber()).collect(Collectors.toList());
        return new SalesTop10ReportVO(StringUtils.join(nameList,","),StringUtils.join(numberList,","));
    }

    /**
     * 导出运营数据到excel
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询最近30天的数据
        LocalDate now = LocalDate.now();
        LocalDate begin=now.minusDays(30);
        LocalDate end=now.minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //2.通过POI写入excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            XSSFRow row = sheet1.getRow(1);
            row.getCell(1).setCellValue("时间: "+begin+"至"+end);
            row= sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row=sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            int start_index=7;
            for(int i=0;i<30;++i){
                LocalDate date=begin.plusDays(i);
                businessData= workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet1.getRow(start_index + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //3.通过输出流客户端下载excel
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            excel.close();
            outputStream.close();;
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }
}
